#include "actionrelativepos.h"
#include <Windows.h>

ActionRelativePos::ActionRelativePos()
{
    classname = __FUNCTION__;
    actParam = QJsonObject();
}

ActionRelativePos::ActionRelativePos(int dx, int dy)
{
    classname = __FUNCTION__;
    actParam = QJsonObject();
    actParam.insert("dx",dx);
    actParam.insert("dy",dy);

    syswidth = ::GetSystemMetrics(SM_CXSCREEN);
    sysheight = ::GetSystemMetrics(SM_CYSCREEN);
}

void ActionRelativePos::setInputKey(QString xkey, QString ykey)
{
    actParam.insert("xkey",xkey);
    actParam.insert("ykey",ykey);
}

ExecuteRet ActionRelativePos::execute()
{
    int dx = actParam.value("dx").toInt();
    int dy = actParam.value("dy").toInt();
    QString xkey = actParam.value("xkey").toString();
    QString ykey = actParam.value("ykey").toString();
    if(xkey.isEmpty()) xkey = "x";
    if(ykey.isEmpty()) ykey = "y";
    int x = prevResult.value(xkey).toInt() + dx;
    int y = prevResult.value(ykey).toInt() + dy;
    qInfo()<<classname<<"mouse to ("<<x<<","<<y<<")";
    INPUT input[4];
    memset(input,0,sizeof(INPUT)*4);
    int inputIndex = 0;
    DWORD timestamp = 1;
    input[inputIndex].type = INPUT_MOUSE;
    input[inputIndex].mi.dwFlags = MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE;
    input[inputIndex].mi.dx = x*65536/syswidth;
    input[inputIndex].mi.dy = y*65536/sysheight;
    input[inputIndex].mi.time = 0;
    ++inputIndex; timestamp+=10;
    SendInput(inputIndex,input,sizeof(INPUT));
    QThread::msleep(50);

    actResult = prevResult; //传递.
    return ERSucc;
}
